package com.example.common.util.weatherutil;

import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class WeatherParser {

    public static List<WeatherData> parseHtml(String html) {
        List<WeatherData> weatherList = new ArrayList<>();

        Document doc = Jsoup.parse(html);
        Elements table = doc.select("table.history-table");

        // 解析历史天气数据表格
        Elements rows = table.select("tr");
        // 去掉表头行
        rows.remove(0);

        // 解析每一行数据，构造 WeatherData 对象
        List<WeatherData> weatherDataList = new ArrayList<>();
        for (Element row : rows) {
            Elements cells = row.select("td");
            String date = cells.get(0).text();
            int highTemp = Integer.parseInt(cells.get(1).text().replace("°", ""));
            int lowTemp = Integer.parseInt(cells.get(2).text().replace("°", ""));
            String amCondition = cells.get(3).text();
            String pmCondition = cells.get(3).text();
            String wind = cells.get(4).text();
            int aqi = Integer.parseInt(cells.get(5).select("span").text().split(" ")[0]);
            WeatherData weatherData = new WeatherData(date, highTemp, lowTemp, amCondition, pmCondition, wind, aqi);
            weatherDataList.add(weatherData);
        }

        return weatherDataList;
    }

}
